﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Main
{
    public partial class SearchCustomers : System.Web.UI.Page
    {
        ControlCustomers.Control cust = new ControlCustomers.Control();
        ControlInvoices.Control inv = new ControlInvoices.Control();
        ControlProducts.Control prod = new ControlProducts.Control();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["ID"] != null)
            {

            }
            else
                Response.Redirect("Login.aspx");

            if (!IsPostBack)
            {               
                Dictionary<int, String> prodList = prod.ViewProductAsDict(Session["Company"].ToString());

                //adds existing products to dropdownlist
                foreach (KeyValuePair<int, String> item in prodList)
                {
                    ListItem prodItem = new ListItem();
                    prodItem.Text = item.Value;
                    prodItem.Value = item.Key.ToString();
                    ddlProduct.Items.Add(prodItem);
                }
            }
        }

        /// <summary>
        /// searches throughout existing customers for matching criteria
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                tblCreateInvoice.Visible = false;
                if (txtSearch.Text.Length > 0)
                {
                    listResult.Items.Clear();
                    if (!ListMatchingCustomers(cust.ViewCustomer(Session["Company"].ToString()), txtSearch.Text))
                    {
                        lblError.Visible = true;
                        lblError.Text = "No customer found!";
                        tblResult.Visible = false;
                        tblBtn.Visible = false;
                        tblInvoice.Visible = false;
                        tblCreateInvoice.Visible = false;
                    }
                }
                else
                {
                    listResult.Items.Clear();
                    if (!ListAllCustomers(cust.ViewCustomer(Session["Company"].ToString())))
                    {
                        lblError.Visible = true;
                        lblError.Text = "No customer found!";
                        tblResult.Visible = false;
                        tblBtn.Visible = false;
                        tblInvoice.Visible = false;
                        tblCreateInvoice.Visible = false;
                    }
                }
            }
            catch (Exception ex)
            {
                lblError.Visible = true;
                lblError.Text = ex.ToString();
            }
        }

        /// <summary>
        /// returns customer info if criteria matched
        /// </summary>
        /// <param name="list"></param>
        /// <param name="searchValue"></param>
        /// <returns></returns>
        private Boolean ListMatchingCustomers(List<Customer> list, string searchValue)
        {
            TechnoStoreMainDataContext db = new TechnoStoreMainDataContext();
            var custQuery = from u in db.Customers
                            where u.name.Contains(searchValue) == true || u.surname.Contains(searchValue) == true || u.email.Contains(searchValue) == true || u.company.Contains(searchValue) == true
                            select u.ID;
            int[] matchedCustID = custQuery.ToArray();

            if (list.Count == 0)
                return false;
            else if (matchedCustID.Length == 0)
                return false;
            else
            {
                foreach (var customerList in list)
                {
                    foreach (var customerID in matchedCustID)
                    {
                        if (customerList.ID == customerID)
                        {
                            ListItem custItem = new ListItem();
                            custItem.Text = customerList.name + " " + customerList.surname + ", " + customerList.email + " - " + customerList.phone + " - " + customerList.address + " - " + customerList.company;
                            listResult.Items.Add(custItem);
                        }
                        else if (customerList.ID != customerID && listResult.Items.Count < 0)
                            return false;
                    }
                }
                tblBtn.Visible = true;
                tblResult.Visible = true;
                lblError.Visible = false;
                tblInvoice.Visible = false;
                db.Dispose();
                return true;
            }
        }

        /// <summary>
        /// returns customer info for all existing customers
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        private Boolean ListAllCustomers(List<Customer> list)
        {
            foreach (var Result in list)
            {
                if (list.Count == 0)
                {
                    return false;
                }
                else
                {
                    ListItem custItem = new ListItem();
                    custItem.Text = Result.name + " " + Result.surname + ", " + Result.email + " - " + Result.phone + " - " + Result.address + " - " + Result.company;
                    listResult.Items.Add(custItem);
                }
            }
            tblResult.Visible = true;
            tblBtn.Visible = true;
            lblError.Visible = false;
            tblInvoice.Visible = false;
            return true;
        }

        /// <summary>
        /// shows list of existing invoices of the related customer
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnShow_Click(object sender, EventArgs e)
        {
            try
            {
                if (listResult.SelectedIndex != -1)
                {
                    listInvoice.Items.Clear();
                    ddlProduct.SelectedIndex = 0;
                    txtAmonut.Text = String.Empty;
                    lblInvoiceError.Text = String.Empty;

                    TechnoStoreMainDataContext db = new TechnoStoreMainDataContext();
                    string selectedCustName = listResult.SelectedItem.ToString().Substring(0, listResult.SelectedItem.ToString().IndexOf(' '));
                    string selectedCustSurname = listResult.SelectedItem.ToString().Substring(listResult.SelectedItem.ToString().IndexOf(' ') + 1, (listResult.SelectedItem.ToString().IndexOf(',') - listResult.SelectedItem.ToString().IndexOf(' ') - 1));

                    var custQuery = from u in db.Customers
                                    where u.name == selectedCustName && u.surname == selectedCustSurname
                                    select u.ID;

                    if (!ListMatchingInvoices(custQuery.SingleOrDefault()))
                    {
                        lblError.Visible = true;
                        lblError.Text = "No invoice found!";
                        tblCreateInvoice.Visible = true;
                        listInvoice.Visible = false;
                    }
                }
                else
                {
                    lblError.Text = "Please select a customer!";
                    lblError.Visible = true;
                    tblCreateInvoice.Visible = false;
                    listInvoice.Visible = false;
                }
            }
            catch (Exception ex)
            {
                lblError.Visible = true;
                lblError.Text = ex.ToString();
            }
        }

        /// <summary>
        /// returns invoice info for all existing invoices
        /// </summary>
        /// <param name="searchValue"></param>
        /// <returns></returns>
        private Boolean ListMatchingInvoices(int searchValue)
        {
            TechnoStoreMainDataContext db = new TechnoStoreMainDataContext();
            var invQuery = from u in db.Invoices
                            where u.customerno == searchValue
                            select u;

            if (invQuery.ToArray().Length == 0)
                return false;
            else
            {
                foreach (var result in invQuery.ToArray())
                {
                    ListItem invItem = new ListItem();
                    invItem.Text = "InvoiceNo: " + result.ID + " Product: " + result.Product.name + " -Price: $" + result.Product.price + " -Amount: " + result.amount + " -Total Price: $" + result.totalprice;
                    listInvoice.Items.Add(invItem);
                }
                tblInvoice.Visible = true;
                lblError.Visible = false;
                tblCreateInvoice.Visible = true;
                listInvoice.Visible = true;
                return true;
            }
        }

        /// <summary>
        /// triggers creation of a new invoice for related customer and selecte product on SQL Azure
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string selectedCustName = listResult.SelectedItem.ToString().Substring(0, listResult.SelectedItem.ToString().IndexOf(' '));
                string selectedCustSurname = listResult.SelectedItem.ToString().Substring(listResult.SelectedItem.ToString().IndexOf(' ') + 1, (listResult.SelectedItem.ToString().IndexOf(',') - listResult.SelectedItem.ToString().IndexOf(' ') - 1));
                
                TechnoStoreMainDataContext db = new TechnoStoreMainDataContext();
                var custQuery = from u in db.Customers
                                where u.name == selectedCustName || u.surname == selectedCustSurname
                                select u.ID;

                var prodIdQuery = from o in db.Products
                                  where o.name == ddlProduct.SelectedItem.ToString()
                                  select o.ID;

                var prodPriceQuery = from o in db.Products
                                     where o.name == ddlProduct.SelectedItem.ToString()
                                     select o.price;

                String msg = inv.CreateInvoice(Convert.ToInt32(custQuery.SingleOrDefault()), Convert.ToInt32(prodIdQuery.SingleOrDefault()), Convert.ToInt32(txtAmonut.Text), Session["Company"].ToString());

                if (msg == String.Empty)
                {
                    lblInvoiceError.Visible = true;
                    lblInvoiceError.Text = "New invoice has been successfully created!";
                    listInvoice.Visible = true;
                    listInvoice.Items.Clear();
                    ListMatchingInvoices(custQuery.SingleOrDefault());
                }
                else
                    lblInvoiceError.Visible = true;
                    lblInvoiceError.Text = msg;
            }
            catch (Exception ex)
            {
                lblInvoiceError.Visible = true; 
                lblInvoiceError.Text = ex.ToString();
            }
        }

        /// <summary>
        /// makes all fields blank
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnReset_Click(object sender, EventArgs e)
        {
            ddlProduct.SelectedIndex = 0;
            txtAmonut.Text = String.Empty;
            lblInvoiceError.Text = String.Empty;
        }
    }
}